import time
from PIL import Image
import board, digitalio
from adafruit_rgb_display import st7735
from picamera2 import Picamera2
from libcamera import Transform

# ========= 1) 初始化 SPI & TFT =========
spi = board.SPI()

cs  = digitalio.DigitalInOut(board.D23)
dc  = digitalio.DigitalInOut(board.D24)
rst = digitalio.DigitalInOut(board.D25)

display = st7735.ST7735R(
    spi,
    cs=cs,
    dc=dc,
    rst=rst,
    baudrate=24000000,
    width=128,
    height=160,
    rotation=0,
    bgr=True
)

PANEL_W, PANEL_H = display.width, display.height
print(f"✅ ST7735R 初始化完成，display.size = {PANEL_W}x{PANEL_H}")

# 自检：红绿蓝
for color in [(255,0,0), (0,255,0), (0,0,255)]:
    img = Image.new("RGB", (PANEL_W, PANEL_H), color)
    display.image(img)
    time.sleep(0.3)

# ========= 2) 摄像头 =========
picam2 = Picamera2()
# 调整摄像头输出尺寸为竖屏友好比例（接近屏幕的128x160）
cfg = picam2.create_preview_configuration(
    main={"size": (240, 320)},  # 改为竖屏尺寸（宽240，高320），方便旋转后裁剪
    transform=Transform(hflip=1, vflip=1)  # 翻转根据实际画面调整
)
picam2.configure(cfg)
picam2.start()
print("✅ 摄像头启动成功")

def to_panel(img: Image.Image) -> Image.Image:
    """优化图像转换逻辑"""
    if img.mode != "RGB":
        img = img.convert("RGB")
    
    # 方案1：直接缩放（适合对比例要求不高的场景）
    # img = img.resize((PANEL_W, PANEL_H), Image.BILINEAR)
    
    # 方案2：保持比例裁剪后缩放（避免拉伸，推荐）
    # 计算缩放比例
    scale = min(PANEL_W / img.width, PANEL_H / img.height)
    new_w = int(img.width * scale)
    new_h = int(img.height * scale)
    img = img.resize((new_w, new_h), Image.BILINEAR)
    
    # 居中裁剪到屏幕尺寸
    left = (new_w - PANEL_W) // 2
    top = (new_h - PANEL_H) // 2
    img = img.crop((left, top, left + PANEL_W, top + PANEL_H))
    
    return img

try:
    # 增加摄像头预热
    time.sleep(2)
    while True:
        # 改用capture_image直接获取PIL图像，避免numpy转换问题
        img = picam2.capture_image("main")
        if img is None:
            print("未获取到图像")
            time.sleep(0.1)
            continue
            
        img = to_panel(img)
        
        # 调试信息
        if 'once' not in globals():
            print(f"[DEBUG] 图像尺寸: {img.size}, 屏幕尺寸: {PANEL_W}x{PANEL_H}")
            globals()['once'] = True
        
        display.image(img)
        time.sleep(0.05)  # 降低刷新频率，避免总线冲突

except KeyboardInterrupt:
    print("\n已退出")
finally:
    picam2.stop()
    display.fill(0x000000)